package your.company.tables;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;
import org.apache.log4j.Logger;
import org.richfaces.component.UIExtendedDataTable;

import your.company.tables.model.capitals.Capital;

@ManagedBean
@SessionScoped
public class CapitalsBean implements Serializable {

   private static final long serialVersionUID = -1509108399715814302L;
   private static final Logger log = Logger.getLogger(CapitalsBean.class);
   @ManagedProperty(value = "#{capitalsParser.capitalsList}")
   private List<Capital> capitals;
   private Collection<Object> selectionRowKeys = new ArrayList<Object>();
   //private List<Capital> selectionItems = new ArrayList<Capital>();
   private Capital selectedItem = null;


   public CapitalsBean() {
   }

   public List<Capital> getCapitals() {
      return capitals;
   }

   public void setCapitals(List<Capital> capitals) {
      this.capitals = capitals;
   }

   public Collection<Object> getSelection() {
      log.info("getSelection: " + selectionRowKeys.size());
      return selectionRowKeys;
   }

   public void setSelection(Collection<Object> selection) {
      /** is not explicitely called by framework,
       *  obviously the element is added to the collection retrieved by getSelection()
       */
   }

   public void selectionListener(AjaxBehaviorEvent event) {
      log.info("selectionListener: " + event);

      log.info("setSelection: " + selectionRowKeys.size());
      for (Object o : selectionRowKeys.toArray()) {
         log.info(o.getClass().getName() + " " + o);
      }
      this.selectionRowKeys = selectionRowKeys;

      UIExtendedDataTable dataTable = (UIExtendedDataTable) event.getComponent();
      dataTable.setRowKey(((ArrayList) selectionRowKeys).get(0));
      selectedItem = (Capital) dataTable.getRowData();

      log.info("selectionListener: " + getSelectedItem());

      /* to be used for multiply selection mode
      UIExtendedDataTable dataTable = (UIExtendedDataTable) event.getComponent();
      Object originalKey = dataTable.getRowKey();
      selectionItems.clear();
      for (Object selectionKey : selection) {
      dataTable.setRowKey(selectionKey);
      if (dataTable.isRowAvailable()) {
      selectionItems.add((Capital) dataTable.getRowData());
      }
      }
      dataTable.setRowKey(originalKey);*/
   }

   public Capital getSelectedItem() {
      return selectedItem;
   }

   public void menu() {
      // dummy method
   }

   public boolean getProperty() {
      return true;
   }

   public void setProperty(boolean value) {
   }
}
